<template>
  <div style="padding: 20px">
    <div style="margin-bottom: 10px">
      设备：<el-select
        style="width: 240px"
        v-model="state.deviceid"
        placeholder="请选择设备"
        @change="handleDeviceChange"
      >
        <el-option
          v-for="item in state.devices"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-button @click="getnoendcount" v-if="devices[state.deviceid] == '1'">
        添加测试批次
      </el-button>
    </div>

    <el-form
      v-if="state.deviceid"
      :model="state.queryParams.condition"
      ref="queryRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="批次名称" prop="nickname">
        <el-input
          v-model="state.queryParams.condition.batchname"
          placeholder="请输入批次名称"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>
    <el-table v-if="state.deviceid" :data="state.testlist" style="width: 100%">
      <!-- <el-table-column prop="id" label="自增主键" width="120" /> -->
      <el-table-column prop="batchname" label="批次名称" width="120" />
      <el-table-column prop="enableboardstatus" label="板卡启用情况" />
      <el-table-column prop="controltype" label="控制类型" width="100">
        <template #default="{ row }">
          <el-tag>
            {{ row.controltype == "Local" ? "本地" : "远程" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="systemvoltage" label="系统电压" width="100" />
      <el-table-column prop="systemcurrent" label="系统电流" width="100" />
      <el-table-column prop="starttime" label="开始时间" width="170" />
      <el-table-column prop="endtime" label="结束时间" width="170" />
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-space :size="size" :spacer="spacer">
            <el-icon
              v-if="devices[state.deviceid] == '1'"
              @click="openDialog(row)"
              title="测试中心"
            >
              <View />
            </el-icon>
            <el-icon
              title="开始测试"
              v-if="devices[state.deviceid] == '1' && row.starttime == null"
              @click="sendControlData(row, '开始')"
            >
              <VideoPlay />
            </el-icon>
            <el-icon
              title="曲线数据"
              v-if="devices[state.deviceid] == '1' && row.starttime != null"
              @click="openJCdataCenterDialog(row)"
            >
              <TrendCharts />
            </el-icon>
            <el-icon
              title="carm 数据"
              v-if="
                devices[state.deviceid] == '1' &&
                row.starttime != null &&
                state.deviceinfo.type == 'ic'
              "
              @click="openJCCramdataCenterDialog(row)"
            >
              <data-board />
            </el-icon>
            <el-icon
              title="结束测试"
              v-if="
                devices[state.deviceid] == '1' &&
                row.starttime != null &&
                row.endtime == null
              "
              @click="sendControlData(row, '结束')"
            >
              <SwitchButton />
            </el-icon>

            <el-icon @click="openOperateLogDialog(row)" title="操作日志">
              <Operation />
            </el-icon>
          </el-space>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="state.total > 0"
      :total="state.total"
      v-model:page="state.queryParams.pageNum"
      v-model:limit="state.queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      v-model="state.testcenterVisible"
      title="测试中心"
      width="90%"
      body-class="testcenter-dialog"
      :destroy-on-close="true"
    >
      <TestCenter
        :type="state.deviceinfo.type"
        :deviceid="state.deviceinfo.id"
        :testid="currentTest.id"
        :testInfo="currentTest"
        :datasourceindex="state.deviceinfo.datasourceindex"
        :enableboardstatus="currentTest.enableboardstatus"
      ></TestCenter>
    </el-dialog>

    <el-dialog
      v-model="state.testconfigVisible"
      title="配置中心"
      width="90%"
      body-class="testcenter-dialog"
      :destroy-on-close="true"
    >
      <TestConfigIC
        v-if="state.deviceinfo.type == 'ic'"
        :datasourceindex="state.deviceinfo.datasourceindex"
        :testid="currentTest.id"
        :deviceid="state.deviceinfo.id"
        :type="state.deviceinfo.type"
        :enableboardstatus="currentTest.enableboardstatus"
      ></TestConfigIC>
      <TestConfig
        v-else
        :datasourceindex="state.deviceinfo.datasourceindex"
        :testid="currentTest.id"
        :deviceid="state.deviceinfo.id"
        :type="state.deviceinfo.type"
        :enableboardstatus="currentTest.enableboardstatus"
      ></TestConfig>
    </el-dialog>
    <el-dialog
      v-model="state.jcdatacenterVisible"
      title="曲线数据"
      width="90%"
      body-class="testcenter-dialog"
      :destroy-on-close="true"
    >
      <JCdataCenterLine
        v-if="state.deviceinfo.type == 'ic'"
        :datasourceindex="state.deviceinfo.datasourceindex"
        :testid="currentTest.id"
        :deviceid="state.deviceinfo.id"
        :type="state.deviceinfo.type"
        :testInfo="currentTest"
        :enableboardstatus="currentTest.enableboardstatus"
      />
      <GLdataCenterLine
        v-else
        :datasourceindex="state.deviceinfo.datasourceindex"
        :testid="currentTest.id"
        :deviceid="state.deviceinfo.id"
        :type="state.deviceinfo.type"
        :testInfo="currentTest"
        :enableboardstatus="currentTest.enableboardstatus"
      >
      </GLdataCenterLine>
    </el-dialog>
    <el-dialog
      v-model="state.jcdataCramVisible"
      title="测试数据"
      width="90%"
      body-class="testcenter-dialog"
      :destroy-on-close="true"
    >
      <CramDataTable
        :datasourceindex="state.deviceinfo.datasourceindex"
        :testid="currentTest.id"
        :deviceid="state.deviceinfo.id"
        :type="state.deviceinfo.type"
        :testInfo="currentTest"
        :enableboardstatus="currentTest.enableboardstatus"
      >
      </CramDataTable>
    </el-dialog>
    <el-dialog
      v-model="state.operateLogVisible"
      title="操作日志"
      width="90%"
      body-class="testcenter-dialog"
      :destroy-on-close="true"
    >
      <device-operate-log
        :deviceid="state.deviceinfo.id"
        :batchname="currentTest.batchname"
      ></device-operate-log>
    </el-dialog>
  </div>
</template>

<script setup>
import { getPage, noendcount } from "@/api/device/testbatch";
import { ref, reactive, onMounted, getCurrentInstance, watch } from "vue";
import { devicelist } from "@/api/system/device.js";
import TestCenter from "@/views/testcenter/index";
import TestConfig from "@/views/testconfig/index";
import TestConfigIC from "@/views/testconfig/indexic";
import { ElMessage, ElMessageBox } from "element-plus";
import { sendControl } from "@/api/device/mqttSend";
import DeviceOperateLog from "@/views/operateLog/deviceOperateLog.vue";
import JCdataCenterLine from "@/views/datacenter/jcdatacenterline.vue";
import GLdataCenterLine from "@/views/datacenter/gldatacenterline.vue";
import CramDataTable from "@/views/datacenter/cramDataTable.vue";
import useUserStore from "@/store/modules/user";
const devices = useUserStore().devices || {};
const props = defineProps({
  type: {
    type: String,
    default: "ic",
  },
  datasourceindex: {
    type: String,
    default: "",
  },
});
const { proxy } = getCurrentInstance();
// 定义响应式状态
const state = reactive({
  devices: [],
  testlist: [],
  queryParams: { pageNum: 1, pageSize: 10, condition: {} },
  total: 0,
  testcenterVisible: false,
  testconfigVisible: false,
  jcdatacenterVisible: false,
  jcdataCramVisible: false,
  deviceinfo: {},
  deviceid: "",
});

// 定义设备选择改变时的处理函数
const handleDeviceChange = (deviceid) => {
  state.deviceinfo = state.devices.filter((item) => item.id == deviceid)[0];
  state.deviceid = deviceid;
  state.testlist = [];
  state.total = 0;
  state.queryParams.condition.batchname = undefined;
  getList();
};
const sendControlData = (row, operation) => {
  ElMessageBox.confirm(`确定要${operation}此测试批次吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const dataToSend = {
        datasourceindex: state.deviceinfo.datasourceindex,
        type: state.deviceinfo.type,
        deviceid: state.deviceinfo.id,
        message: {
          type: operation,
          batchname: row.batchname,
        },
      };

      sendControl(dataToSend).then((res) => {
        ElMessage.success(`${operation}指令已发送`);
        getList();
      });
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};
// 定义对话框相关状态

const currentTest = ref({});
function resetQuery() {
  proxy.resetForm("queryRef");
  state.queryParams.condition.batchname = undefined;
}
// 打开对话框
const openDialog = (row = {}) => {
  currentTest.value = { ...row };
  state.testcenterVisible = true;
};
const openJCdataCenterDialog = (row) => {
  currentTest.value = { ...row };
  state.jcdatacenterVisible = true;
};

const openJCCramdataCenterDialog = (row) => {
  currentTest.value = { ...row };
  state.jcdataCramVisible = true;
};
const openOperateLogDialog = (row) => {
  currentTest.value = { ...row };
  state.operateLogVisible = true;
};

const getnoendcount = () => {
  noendcount({
    type: state.deviceinfo.type,
    datasourceindex: state.deviceinfo.datasourceindex,
  }).then((res) => {
    if (res > 0) {
      ElMessage.warning("当前有未结束的测试批次，不能添加新的测试批次");
    } else {
      state.testconfigVisible = true;
    }
  });
};

const getList = () => {
  getPage({
    ...state.queryParams,
    type: state.deviceinfo.type,
    datasourceindex: state.deviceinfo.datasourceindex,
  }).then((res) => {
    state.testlist = res.records;
    state.total = res.total;
  });
};

// 组件挂载时获取设备数据
onMounted(() => {
  devicelist({}).then((res) => {
    state.devices = res.filter((item) => useUserStore().devices[item.id]);
    if (state.devices[0]) {
      state.deviceinfo = state.devices[0];
      // console.log(state.deviceinfo);
      state.deviceid = state.devices[0].id;
      getList();
    }
  });
});
</script>
<style scoped>
.testcenter-dialog {
  max-height: 80vh;
}
</style>
